package per.dg.basicusehandler

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    private val mHandler : Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                0 ->{
                    if(msg.obj == null){
                        tvShow.setText("empty messenge received")
                    }
                }
                1 ->{
                    tvShow.setText(msg.obj as String)
                }
            }
        }
    }

    private lateinit var tvShow : TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvShow = findViewById(R.id.tv_show)
    }

    fun onClick(view: View) {
        when(view.id){
            R.id.bt_start_thread_and_send_messenge_to_ui -> {
                startThreadAndSendMessengeToUI()
            }
            R.id.bt_delay_5s_send_null_messenge ->{
                delay5sSendNullMessenge()
            }
            R.id.bt_remove_all_send_messenges ->{
                mHandler.removeCallbacksAndMessages(null)
            }
        }
    }

    private fun startThreadAndSendMessengeToUI(){
        Thread(object : Runnable {
            override fun run() {
                var message = Message()
                message.what = 1
                message.obj = "i am worker, want to change the ui"
                mHandler.sendMessage(message)
            }
        }).run()
    }

    private fun delay5sSendNullMessenge(){
        mHandler.sendEmptyMessageDelayed(0, 5*1000)
    }
}